#include <8052.h>
#include "misc.h"
#include "keyborad.h"

//点击直接点亮LED
void keybord_show_led(void)
{
    unsigned char p3Value;
    while (1)
    {
        //将P3口直接输入给P1 LED口
        //键盘s2-s5直连的d5-d8
        p3Value = P3;
        P1 = p3Value;
    }
}

//循环显示数字
void keybord_show_num(void)
{

    P0 = 0x2B; //101011B
    P2_7 = 1;  //开启位选 //低电位显示，数码管位置与二进制是反的
    P2_7 = 0;  //关闭位选

    char i = 0;
    do
    {
        P0 = TBL_DIGITAL_DISPALY[i];
        P2_6 = 1; //开启段选
        P2_6 = 0; //关闭段选

        //以下两阻塞模拟按键按下抬起的操作
        //P3_5对应S3按键，点下为低电平
        //高电阻塞
        while (P3_5)
        {
            //延时消抖
            //delay(1);
        }
        //延时消抖
        delay(50);
        //低电阻塞
        while (!P3_5)
        {
            //延时消抖
            //delay(1);
        }
        //延时消抖
        delay(50);

        i++;
        if (i >= 10)
        {
            i = 0;
        }
    } while (1);
}

//根据矩阵键盘显示数字
void keybord_show_4x4(void)
{
    //重置段选位选
    P2_6 = P2_7 = 0;

    P0 = 0x2A; //101010B
    P2_7 = 1;  //开启位选 //低电位显示，数码管位置与二进制是反的
    P2_7 = 0;  //关闭位选

    char keys[] = {0b1110, 0b1101, 0b1011, 0b0111};

    while (1)
    {
        //执行矩阵键盘扫描
        for (char i = 0; i < sizeof(keys); i++)
        {
            P3 = keys[i] | 0b11110000;
            char p3data = P3; //要把值取出来使用，否则可能会有问题
            char h_data = p3data >> 4;
            for (char j = 0; j < sizeof(keys); j++)
            {
                if (h_data == keys[j])
                {
                    unsigned int digital_index = i * 4 + j;
                    P0 = TBL_DIGITAL_DISPALY[digital_index];
                    P2_6 = 1; //开启段选
                    P2_6 = 0; //关闭段选

                    //P2_3为蜂鸣器
                    P2_3 = 0;  //开启
                    delay(10); //约为20ms
                    P2_3 = 1;  //关闭

                    //跳出两层循环，采用goto
                    goto LBL_END_KBD_SCAN;
                }
            }
        }

    //标签，结束扫描
    LBL_END_KBD_SCAN:
        continue; //只为让编译器不报警告
    }
}